<?php

namespace App\Http\Requests\VisitWebTask;

use Illuminate\Foundation\Http\FormRequest;

class Create extends FormRequest
{
    private $body;
    private $sign;
    public function getBody(){
        return $this->body;
    }
    public function getSign(){
        return $this->sign;
    }
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    /*    public function authorize()
        {
            return $this->post('sign') == $this->sign();
        }*/

    static function sign($data, $agent)
    {
        if ($agent) {
            $data['key'] = $agent['key'];
            unset($data['sign']);

            $string = self::makeBody($data);
            $sign = sha1($string);
            return $sign;
        }
        return false;
    }

    static function makeBody($data)
    {
        ksort($data);
        return implode('', $data);
    }

    static function getAgent($user_id)
    {
        $data = ['dillon' => ['key' => '62328359e91d4']];
        return @$data[$user_id];
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'time' => 'bail|required|date|after:-10 minutes',
            'url' => 'bail|required|url',
            'agent_code' => 'bail|required',
            'sign' => 'bail|required',
//            'device_id' => 'bail|required',
        ];
    }

    /**
     * 配置验证器实例。
     *
     * @param \Illuminate\Validation\Validator $validator
     * @return void
     */
    public function withValidator($validator)
    {
        if (!$validator->validate()) {
            return;
        }
        $validator->after(function ($validator) {
            $validated = $validator->validated();
            if (!self::getAgent($validated['agent_code'])) {
                $validator->errors()->add('agent_code', 'agent不存在');
                return false;
            }
            if ($validated['sign'] != $this->sign($validated, self::getAgent($validated['agent_code']))) {
                $validator->errors()->add('sign', '签名错误');
                return false;
            }
        });
    }

}
